'use strict';

exports.main = async (event, context) => {
  const { code, token } = event;
  
  if (!token) {
    return {
      success: false,
      message: '未登录或登录已过期'
    };
  }
  
  if (!code) {
    return {
      success: false,
      message: '卡密不能为空'
    };
  }

  try {
    const db = uniCloud.database();
    
    // 验证管理员权限
    const adminCollection = db.collection('admin');
    const adminQuery = await adminCollection.where({
      token: token
    }).get();
    
    if (!adminQuery.data || adminQuery.data.length === 0) {
      return {
        success: false,
        message: '未登录或登录已过期'
      };
    }
    
    const codeCollection = db.collection('activation_codes');
    
    // 查询卡密是否存在
    const { data } = await codeCollection.where({
      code: code
    }).get();
    
    if (!data || data.length === 0) {
      return {
        success: false,
        message: '卡密不存在'
      };
    }
    
    // 重置卡密状态
    const updateData = {
      status: 'unused',  // 重置为未使用状态
      deviceId: null,    // 清除设备绑定
      lastLoginTime: null,
      lastLoginIP: null,
      lastLoginUA: null,
      updateTime: Date.now()
    };
    
    await codeCollection.where({
      code: code
    }).update(updateData);
    
    return {
      success: true,
      message: '卡密重置成功'
    };
  } catch (error) {
    console.error('重置卡密失败:', error);
    return {
      success: false,
      message: '重置卡密失败：' + error.message
    };
  }
}; 